package com.henushang.ranking.dao.impl;

import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.springframework.stereotype.Repository;

import com.henushang.ranking.dao.CategoryInfoDao;
import com.henushang.ranking.domain.CategoryInfo;
import com.henushang.ranking.domain.WebsiteInfo;
import com.henushang.ranking.util.mongo.MongoUtil;
import com.mongodb.client.MongoCollection;

@Repository("categoryInfoDao")
public class CategoryInfoDaoImpl implements CategoryInfoDao {

    private static String collectionName = "category_info";
    private static MongoCollection<WebsiteInfo> coll = null;

    @Override
    public String getCollectionName() {
        return collectionName;
    }

    @Override
    public boolean insert(CategoryInfo categoryInfo) {
        return insertOne(categoryInfo);
    }

    public CategoryInfo getOne(String _id) {

        return findOneById(_id);
    }

    public boolean delete(String _id) {

        return deleteById(_id);
    }

    public List<CategoryInfo> getListByQueryMap(Map<String, Object> queryMap) {

        return findList(queryMap);
    }

    @Override
    public boolean update(CategoryInfo categoryInfo) {
        return updateById(categoryInfo);
    }

    @Override
    public MongoCollection<WebsiteInfo> getColl() {
        if (coll == null) {
            try {
                coll = MongoUtil.getColl(getCollectionName());
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(1);
            }
        }
        return coll;
    }

    @Override
    public Document toDocument(CategoryInfo categoryInfo) {
        Document document = new Document();
        document.put("_id", categoryInfo.get_id());
        document.put("name", categoryInfo.getName());
        document.put("create_time", categoryInfo.getCreate_time());
        document.put("weight", categoryInfo.getWeight());
        return document;
    }

    @Override
    public CategoryInfo fromDocument(Document document) {
        CategoryInfo info = new CategoryInfo();
        if (document == null) {
            return info;
        }
        info.set_id(document.getString("_id"));
        info.setName(document.getString("name"));
        info.setCreate_time(document.getString("create_time"));
        info.setWeight(document.getInteger("weight"));
        return info;
    }

    public static void main(String[] args) {
        CategoryInfoDao dao = new CategoryInfoDaoImpl();
        String id = "001";
        CategoryInfo info = new CategoryInfo();
        info.set_id(id);
        info.setName("国内外新闻");
        info.setCreate_time("2018-06-05 11:22:11");
        boolean re = dao.insert(info);
        System.out.println(re);
        CategoryInfo info1 = dao.getOne(id);
        System.out.println(info1);
        System.out.println(dao.getOne(id));
        //        boolean d = dao.delete(id);
        //        System.out.println(d);
    }
}
